package com.umeox.watch.moto.alarm.ui;


import android.app.KeyguardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.dialog.ActionOptionsDialog;
import com.umeox.watch.moto.alarm.AlarmDetail;
import com.umeox.watch.moto.alarm.R;
import com.umeox.watch.moto.alarm.Utils;
import com.umeox.watch.moto.alarm.base.BaseApp;
import com.umeox.watch.moto.alarm.base.Constants;
import com.umeox.watch.moto.dataservice.DataProvider;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;


public class TriggerActivity extends ThemeAppCompatActivity implements View.OnClickListener {

    private static final String INCOME_ACTION = TelephonyManager.ACTION_PHONE_STATE_CHANGED;
    private static final String OUT_ACTION = Intent.ACTION_NEW_OUTGOING_CALL;
    public static final int[] ICONS = {R.drawable.alarm_clock_ring, R.drawable.alarm_clock_ring};
    public static final int[] DESTS = {R.string.remind_later_5, R.string.remind_later_10};
    private AlarmDetail triggerAlarm;
    private long[] pattern = {600, 600, 600, 600};
    private Vibrator vibrator;
    private PowerManager.WakeLock wakeLock = null;
    private KeyguardManager.KeyguardLock kl;
    private TelephonyManager tm;
    private Handler mHandler = new Handler();

    private TextView mTimeTv;
    private TextView mAmpmTv;
    private TextView mWeekTv;
    private View mMuteView;
    private View mOptionView;
    private boolean m24HourFormat;
    private AudioManager mAudioManager;
    private MediaPlayer mMediaPlayer;
    private Runnable stopCurrentAlarm = this::finish;
    private Uri mRingtoneUri;
    private float mRingVolume;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_trigger);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mRingVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM) * 1f / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
        initView();
        initListener();
        intiDataFromBundle();

    }


    private void initView() {
        mTimeTv = findViewById(R.id.alarm_time);
        mAmpmTv = findViewById(R.id.alarm_ampm);
        mWeekTv = findViewById(R.id.alarm_repeat_day);
        mMuteView = findViewById(R.id.mute_view);
        mOptionView = findViewById(R.id.later_view);
    }

    private void initListener() {
        mMuteView.setOnClickListener(this);
        mOptionView.setOnClickListener(this);
    }

    private void initData() {
        m24HourFormat = DateFormat.is24HourFormat(this);
        final String alarmTime = triggerAlarm.getAlarmTime();
        mTimeTv.setText(m24HourFormat ? Utils.to24HourFormat(alarmTime, Locale.getDefault()) : Utils.to12HourFormat(alarmTime, Locale.getDefault()));
        mAmpmTv.setVisibility(m24HourFormat ? View.INVISIBLE : View.VISIBLE);
        mAmpmTv.setText(triggerAlarm.getHour() < 12 ? getString(R.string.am) : getString(R.string.pm));
        final String alarmName = triggerAlarm.getAlarmName();
        int currentDayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
        mWeekTv.setText(getResources().getStringArray(R.array.week_days_short)[currentDayOfWeek - 1]);

        wakeUpAndUnlock();
        enableHomeKeyDispatched(getWindow(), true);

        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        initSoundPool();
        mHandler.postDelayed(stopCurrentAlarm, 50 * 1000);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        stopCurrentAlarm();
        intiDataFromBundle();
        playRingTone();
        mHandler.postDelayed(stopCurrentAlarm, 50 * 1000);
    }

    private void intiDataFromBundle() {
        Bundle bundle = getIntent().getExtras();
        long _id = bundle != null ? bundle.getLong(Constants.EXTRA_KEY_ID, 0) : 0;
        if (_id > 0) {
            triggerAlarm = AlarmDetail.convertFromValues(DataProvider.getAlarm(_id));
        }
        if (triggerAlarm == null) {
            Logger.e("no found extra 'alarm'");
            finish();
            return;
        }

        if (triggerAlarm.getAlarmId() == Integer.MAX_VALUE) {
            triggerAlarm.deleteWithoutNotify();
        } else if (triggerAlarm.getRepeatFlag() == 0) {
            //从不重复闹钟，响铃一次关闭
            triggerAlarm.setState(0);
            triggerAlarm.updateWithoutNotify();
            List<AlarmDetail> alarmList = Utils.getAlarmList();
            if (!alarmList.isEmpty()) {
                List<AlarmDetail> needUpdateAlarmList = new ArrayList<>();
                for (AlarmDetail alarmDetail : alarmList) {
                    if (alarmDetail.getAlarmTime().equals(triggerAlarm.getAlarmTime())
                            && alarmDetail.getRepeatFlag() == triggerAlarm.getRepeatFlag()
                            && alarmDetail.getRepeatExpression().equals(triggerAlarm.getRepeatExpression())
                            && alarmDetail.getState() == 1) {
                        needUpdateAlarmList.add(alarmDetail);
                    }
                }
                if(!needUpdateAlarmList.isEmpty()){
                    for (AlarmDetail alarmDetail : needUpdateAlarmList) {
                        alarmDetail.setState(0);
                        alarmDetail.updateWithoutNotify();
                    }
                }
            }
        }

        initData();
    }

    private int[] ringTones = {
            R.raw.alarm_default,
            R.raw.alarm_01,
            R.raw.alarm_02,
            R.raw.alarm_03,
            R.raw.alarm_04,
    };

    private void initSoundPool() {
        mAudioManager.requestAudioFocus(mAudioFocusChangeListener, AudioManager.STREAM_ALARM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
//        mRingtoneUri = getUriFromDrawableRes(this, ringTones[triggerAlarm.getRingType()]);
        mRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
        playRingTone();
    }

    private static final String TAG = "TriggerActivity";

    private void playRingTone() {
        vibrator.vibrate(pattern, 0);

        if (DataProvider.inForbidPeriodNow()
                || Utils.isMute(TriggerActivity.this)
                || Utils.phoneIsInUse(TriggerActivity.this)) {
            return;
        }
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
                mMediaPlayer.setDataSource(this, mRingtoneUri);
                mMediaPlayer.setLooping(true);
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mMediaPlayer.prepare();
            }
            mMediaPlayer.start();
        } catch (Exception e) {
            Log.e(TAG, "playRingTone: ", e);
        }
    }

    /**
     * 得到资源文件中图片的Uri
     *
     * @param context 上下文对象
     * @param id      资源id
     * @return Uri
     */
    public static Uri getUriFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }

    private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {

        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    stopRingTone();
                    if (vibrator != null) {
                        vibrator.cancel();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    mMediaPlayer.setVolume(0.2f, 0.2f);
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    playRingTone();
                    mMediaPlayer.setVolume(mRingVolume, mRingVolume);
                    vibrator.vibrate(0);
                    break;
            }

        }
    };

    private void stopRingTone() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;

        }
    }

    final ActionOptionsDialog.OnClickListener mOptionsDialogClickListener = new ActionOptionsDialog.OnClickListener() {
        @Override
        public void onOption1Click() {
            saveAlarm(5);
        }

        @Override
        public void onOption2Click() {
            saveAlarm(10);
        }

        @Override
        public void onOption3Click() {

        }

        @Override
        public void onOption4Click() {

        }
    };

    private void saveAlarm(int later) {
        try {
            triggerAlarm.later(later).insert();
            finish();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    private void wakeUpAndUnlock() {
        if (kl == null) {
            KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
            kl = km.newKeyguardLock("unLock");
        }
        //解锁
        kl.disableKeyguard();

        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, getClass().getSimpleName());
        }
        // 点亮亮屏
        wakeLock.acquire();
    }

    private void releaseLock() {
        if (wakeLock != null) {
            log("Releasing wakelock");
            try {
                wakeLock.release();
            } catch (Throwable th) {
                log("Releasing wakelock failed:" + th);
            }
        } else {
            log("Wakelock reference is null");
        }
    }

    private synchronized void stopCurrentAlarm() {
        mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
        stopRingTone();
        if (vibrator != null) {
            vibrator.cancel();
        }
        mHandler.removeCallbacks(stopCurrentAlarm);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        releaseLock();
    }

    @Override
    protected void onDestroy() {
        releaseLock();
        stopCurrentAlarm();
        BaseApp.getInstance().scheduleAlarm();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        super.onDestroy();
    }

    private void log(String text) {
        Logger.i(text);
    }

    private void enableHomeKeyDispatched(Window window, boolean enable) {
        final WindowManager.LayoutParams lp = window.getAttributes();
        if (enable) {
            lp.flags |= 0x80000000;
        } else {
            lp.flags &= ~0x80000000;
        }
        window.setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.mute_view) {
            finish();
        } else if (id == R.id.later_view) {
            ActionOptionsDialog optionsDialog = new ActionOptionsDialog(TriggerActivity.this, DESTS, ICONS, this);
            optionsDialog.show();
            optionsDialog.setOnClickListener(mOptionsDialogClickListener);
        }
    }

}
